import { getUserInfoAPI, loginAPI } from '@/api/user'

const { getToken, setToken, removeToken } = require('@/utils/auth')

const state = {
  token: getToken(),
  userInfo: {}
}

const getters = {}

const mutations = {
  setToken(state, token) {
    state.token = token // 储存在vuex中
    setToken(token) // 储存在本地中
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, data) {
    state.userInfo = data
  }
}

const actions = {
  async login(context, data) {
    // 1. 发送请求
    // 2. 获取token
    const res = await loginAPI(data)
    console.log('登陆成功', res)
    // 3. 提交mutations
    context.commit('setToken', res)
  },
  async logout(context) {
    context.commit('removeToken')
    context.commit('setUserInfo', {})
  },
  async getUserInfo(context) {
    const res = await getUserInfoAPI()
    console.log('用户基本信息', res)
    context.commit('setUserInfo', res)
  }
}

export default {
  // 开启命名空间
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
